/*****************************************************************************
 * memory.c : memory allocation and management
 *****************************************************************************
 * Copyright (C) 2011 PELinker
 *
 * Authors: Iceberg <iceberg58744@163.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include <windows.h>

#define MAX_BUFFER_SIZE (1024 * 1024 * 1024)

static BYTE Buffer[MAX_BUFFER_SIZE];
static DWORD Curr;
static DWORD Prev;

void* Malloc(const DWORD size)
{
	DWORD padding = ((size + 0x3) & ~0x3);

	if (0 == size)
	{
		return NULL;
	}

	if (Curr + padding < MAX_BUFFER_SIZE)
	{
		Prev = Curr;
		Curr += padding;
		return Buffer + Prev;
	}
	else
	{
		return NULL;
	}
}

void* Realloc(void * const ptr, const DWORD size)
{
	DWORD padding = ((size + 0x3) & ~0x3);

	if (NULL == ptr)
	{
		return Malloc(size);
	}

	if (ptr != Buffer + Prev)
	{
		return NULL;
	}

	Curr = Prev;
	Curr += padding;

	return ptr;
}

void Memset(void * const dest, const BYTE value, const DWORD size)
{
	BYTE * const p = (BYTE * const)dest;
	DWORD i = 0;

	while (i < size)
	{
		p[i++] = value;
	}
}

void Memcpy(void * const dest, const void * const src, const DWORD size)
{
	const BYTE * const p1 = (const BYTE * const)src;
	BYTE * const p2 = (BYTE * const)dest;
	DWORD i = 0;

	while (i < size)
	{
		p2[i] = p1[i];
		++i;
	}
}

int Memcmp(const void * const arg1, const void * const arg2, const DWORD size)
{
	const BYTE * const p1 = (const BYTE * const)arg1;
	const BYTE * const p2 = (const BYTE * const)arg2;
	DWORD i = 0;

	while (i < size)
	{
		if (p1[i] != p2[i])
		{
			return 1;
		}

		++i;
	}

	return 0;
}
